﻿package model.utils 
{
	import com.asual.swfaddress.SWFAddressEvent;
	import flash.events.EventDispatcher;
	import com.asual.swfaddress.SWFAddress;
	
	/**
	 * ...
	 * @author Lobanov
	 */
	public class SiteSWFAddress extends EventDispatcher
	{
		
		private static var _deeplink:String = "";	
		private var _value:String = "/";	

		private var indexFirstEvent:SWFAddressEvent;
		
		private static var _instance:SiteSWFAddress;
		
		public function SiteSWFAddress() 
		{
			super();
		}
		
		public function init():void 
		{
			if (!SiteModel.indexFirst)
			{
				SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onChange);
				SWFAddress.setHistory(false);
				var v:String = SWFAddress.getValue();
				if (v != "/") SWFAddress.setValue(v);
			}
			else
			{
				onChange(indexFirstEvent);
				indexFirstEvent = null;
			}
		}
		
		private function onChange(event:SWFAddressEvent):void 
		{
			_value = stripStrictSlashes(event.value);
			var validBranch:String = checkDeeplink();
			if (!isInternal)
			{
				if (_value.length > 1) 
				{
					var validated:String = validate(_value);
					if (SiteModel.routing)
					{
						if (validated.length > 0) dispatchGoto(SiteModel.routes[validated] + _deeplink);
						else if (isSinglePage) dispatchGoto(SiteModel.indexID + _deeplink);
						else dispatchGoto(SiteModel.indexID);
					}
					else 
					{
						dispatchGoto(validated);
					}
				} 
				else 
				{
					if (rootBranch && rootBranch.length > 0)
					{
						dispatchGoto(rootBranch);
						rootBranch = null;
					}
					else
					{
						dispatchGoto(SiteModel.indexID);
					}
				}
			}
			dispatchDeeplink(validBranch);
		}
		
		public static function get instance():SiteSWFAddress
		{
			return _instance;
		}
		
		public static function get deeplink():String
		{
			return _deeplink;
		}	
		
	}

}